import React from 'react';
import cls from 'clsx';
import { SkeletonProps } from './PropsType';
import { addUnit, getSizeStyle } from '../utils';
import useNamespace from '../utils/useNamespace';

const DEFAULT_ROW_WIDTH = '100%';
const DEFAULT_LAST_ROW_WIDTH = '60%';

const Skeleton: React.FC<SkeletonProps> = ({
  children,
  className,
  style,
  row = 3,
  rowWidth = DEFAULT_ROW_WIDTH,
  rowHeight,
  avatar,
  avatarShape = 'round',
  avatarSize,
  title,
  titleWidth,
  loading = true,
  animate = true,
  round = true,
}) => {
  const [bem] = useNamespace('skeleton');

  const getRowWidth = (index: number) => {
    if (rowWidth === DEFAULT_ROW_WIDTH && index === row - 1 && index !== 0) {
      return DEFAULT_LAST_ROW_WIDTH;
    }

    if (Array.isArray(rowWidth)) {
      return rowWidth[index];
    }

    return rowWidth;
  };
  const getRowHeight = (index: number) => {
    if (Array.isArray(rowHeight)) {
      return rowHeight[index];
    }

    return rowHeight;
  };

  const renderAvatar = () => {
    if (avatar) {
      return <div className={cls(bem('avatar', avatarShape))} style={getSizeStyle(avatarSize)} />;
    }
    return null;
  };

  const renderTitle = () => {
    if (title) {
      const width = addUnit(titleWidth);
      const height = addUnit(getRowHeight(0));
      return <div className={cls(bem('title'))} style={{ width, height }} />;
    }
    return null;
  };

  const renderRows = () =>
    Array(row)
      .fill('')
      .map((_, i) => {
        const width = addUnit(getRowWidth(i));
        const height = addUnit(getRowHeight(i));
        // eslint-disable-next-line react/no-array-index-key
        return <div key={i} className={cls(bem('row'))} style={{ width, height }} />;
      });

  if (!loading) return children;
  return (
    <div className={cls(className, bem({ animate, round }))} style={style}>
      {renderAvatar()}
      <div className={cls(bem('content'))}>
        {renderTitle()}
        {renderRows()}
      </div>
    </div>
  );
};

export default Skeleton;
